<template>
  <div
    class="scan-input-box"
    :class="disabled ? 'scan-input-box-disabeld' : ''"
  >
    <el-input
      ref="codeInput"
      v-model="code"
      :clearable="true"
      style="width: 400px"
      :disabled="disabled"
      placeholder="请扫码或输入原厂码"
      @keyup.enter.native="sacn"
      @input="(e) => (code = validSe(e))"
    >
      <template #prepend>原厂码</template>
    </el-input>
    <el-dialog
      title="扫描从码"
      width="30%"
      v-model="dialogSubCodeVisible"
      @close="handleSubClose"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div class="scan-dialog">
        <div class="info">
          <div class="name">
            产品名称：{{ productDetail && productDetail.commonName }}产品
          </div>
        </div>
        <el-input
          ref="subCodeRef"
          @keyup.enter.native="sacnSubCode"
          @input="(e) => (inputSubCode = validSe(e))"
          placeholder="请扫描从码"
          v-model="inputSubCode"
          clearable
        ></el-input>
      </div>
      <template #footer class="dialog-footer">
        <el-button @click="handleSubClose">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog
      title="扫描主码"
      width="30%"
      v-model="dialogMainCodeVisible"
      @close="handleMainClose"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div class="scan-dialog">
        <el-input
          ref="mainCodeRef"
          @keyup.enter.native="sacnMainCode"
          @input="(e) => (inputMainCode = validSe(e))"
          placeholder="请扫描主码"
          v-model="inputMainCode"
          clearable
        ></el-input>
      </div>
      <template #footer class="dialog-footer">
        <el-button @click="handleMainClose">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ScanInputBox">
const { proxy } = getCurrentInstance()
const props = defineProps({
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  api: {
    type: Function,
    default: undefined,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  tableData: {
    type: Array,
    default: () => {
      return []
    },
  },
  getProductIds: {
    type: Array,
    default: () => {
      return []
    },
  },
})
const dialogSubCodeVisible = ref(false)
const dialogMainCodeVisible = ref(false)
const inputSubCode = ref('')
const inputMainCode = ref('')
const productDetail = ref(undefined)
const code = ref('')
const mainCode = ref('')

function sacn() {
  if (!code.value) {
    proxy.$message({
      message: '请扫描二维码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  const params = {
    ...props.query,
    code: proxy.$fn.setTrim(code.value),
  }
  props
    .api(params)
    .then((res) => {
      if (res && res.success) {
        const scanState = res.data.flag
        switch (scanState) {
          case 0:
            return scanResult(res.data.productDetail)
          case 1:
            return scanProgressSub()
          case 2:
            return scanProgressMain()
        }
      } else {
        code.value = ''
      }
    })
    .catch((err) => {
      code.value = ''
    })
}
function sacnSubCode() {
  if (code.value) inputMainCode.value = code.value
  const params = {
    ...props.query,
    subCode: proxy.$fn.setTrim(inputSubCode.value),
    mainCode: proxy.$fn.setTrim(inputMainCode.value),
  }
  props
    .api(params)
    .then((res) => {
      if (res && res.success) {
        const flag = res.data && res.data.flag
        if (flag > -1) {
          scanResult(res.data.productDetail)
          handleSubClose()
        } else {
          proxy.$message({
            message: `扫码报错！`,
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
        }
      } else {
        inputSubCode.value = ''
      }
    })
    .catch((err) => {
      inputSubCode.value = ''
    })
}
function sacnMainCode() {
  const params = {
    ...props.query,
    subCode: proxy.$fn.setTrim(code.value),
    mainCode: proxy.$fn.setTrim(inputMainCode.value),
  }
  props
    .api(params)
    .then((res) => {
      if (res && res.success) {
        const flag = res.data && res.data.flag
        if (flag > -1) {
          scanResult(res.data.productDetail)
          handleMainClose()
        } else {
          proxy.$message({
            message: `扫码报错！`,
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
        }
      } else {
        inputMainCode.value = ''
      }
    })
    .catch((err) => {
      inputMainCode.value = ''
    })
}
function generateProductKey(item) {
  //一物一码不加单价作为key,同批号效期视为重复扫码
  if (item.codeType == 3 || item.codeType == 2) {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    return key
  } else {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate +
      '&' +
      item.price
    return key
  }
}
function scanResult(data) {
  let obj = {}
  let dataKey = generateProductKey(data)
  let isSuccess = true
  data.isChioce = true
  data.id = Math.random()
  let indexOf = props.getProductIds.indexOf(data.productId)
  if (indexOf === -1) {
    obj.flag = 3 //1,覆盖，2添加个体，3添加一行数据
    obj.data = data
  }
  props.tableData.forEach((item, index) => {
    // if(item.codeType!)
    if (item.productId === data.productId) {
      data.deliverableCalcQty = item.deliverableCalcQty
      data.deliverableLargeUnitQty = item.deliverableLargeUnitQty
      data.deliverableQty = item.deliverableQty
      data.deliverableSmallUnitQty = item.deliverableSmallUnitQty
      if (item.flag) {
        let details = item.details

        let itemKey = generateProductKey(item)
        // switch(itemKey){
        //   case dataKey:
        //     if (
        //       row.factoryMainCode + row.factorySubCode ===
        //       data.factoryMainCode + data.factorySubCode
        //     ) {
        //       isSuccess = false;
        //     } else {
        //       obj.flag = 2; //1,覆盖，2添加个体，3添加一行数据
        //       obj.index = index;
        //       obj.data = data;
        //     }
        //     break

        // }
        if (itemKey === dataKey) {
          details.forEach((row) => {
            if (
              row.factoryMainCode + row.factorySubCode ===
              data.factoryMainCode + data.factorySubCode
            ) {
              isSuccess = false
            } else {
              obj.flag = 2 //1,覆盖，2添加个体，3添加一行数据
              obj.index = index
              obj.data = data
            }
          })
        } else {
          if (!obj.flag) {
            obj.flag = 3 //1,覆盖，2添加个体，3添加一行数据
            obj.data = data
          }
        }
      } else {
        obj.flag = 1 //1,覆盖，2添加个体，3添加一行数据
        obj.index = index
        obj.data = data
      }
    }
  })
  if (!isSuccess) {
    proxy.$message({
      message: `重复扫码`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    code.value = ''
    return
  }
  proxy.$emit('callback', obj)
  code.value = ''
}

function scanProgressSub(data) {
  dialogSubCodeVisible.value = true
  productDetail.value = { ...data }
  let timer = setTimeout(() => {
    proxy.$refs.subCodeRef.focus()
    clearTimeout(timer)
  }, 100)
}
function scanProgressMain() {
  dialogMainCodeVisible.value = true
  let timer = setTimeout(() => {
    proxy.$refs.mainCodeRef.focus()
    clearTimeout(timer)
  }, 100)
}
function handleClose() {
  inputSubCode.value = undefined
  inputMainCode.value = undefined
  code.value = undefined
  dialogSubCodeVisible.value = false
  dialogMainCodeVisible.value = false
}
function handleSubClose() {
  inputSubCode.value = undefined
  inputMainCode.value = undefined
  code.value = undefined
  dialogSubCodeVisible.value = false
}
function handleMainClose() {
  inputMainCode.value = undefined
  inputSubCode.value = undefined
  code.value = undefined
  dialogMainCodeVisible.value = false
}
</script>

<style scoped></style>
